package org.feng.datasource.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.feng.datasource.DynamicDataSource;
import org.feng.datasource.constant.DataSourceConstant;
import org.feng.datasource.entity.DataSourceProperties;
import org.feng.datasource.entity.SpringDataSourceProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源自动配置
 *
 * @author feng
 */
@Data
@Slf4j
@AutoConfiguration
@ConfigurationPropertiesScan({"org.feng.datasource.entity"})
public class DynamicDataSourceAutoConfiguration {

    @Resource
    private SpringDataSourceProperties springDataSourceProperties;


    /**
     * 构建数据源
     *
     * @param dataSourceProperties 数据源属性配置
     * @return 数据源
     */
    private DataSource dataSource(DataSourceProperties dataSourceProperties) {
        return DataSourceBuilder.create()
                .driverClassName(dataSourceProperties.getDriverClassName())
                .url(dataSourceProperties.getJdbcUrl())
                .username(dataSourceProperties.getUsername())
                .password(dataSourceProperties.getPassword())
                .build();
    }

    @Primary
    @Bean
    public DataSource dynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>(16);

        Map<String, DataSourceProperties> dataSourcePropertiesMap = springDataSourceProperties.getConfigMap();
        dataSourcePropertiesMap.forEach((merchant, properties) -> dataSourceMap.put(merchant, dataSource(properties)));

        // 设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);

        // 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceMap.get(DataSourceConstant.MASTER));
        return dynamicDataSource;
    }


    @PostConstruct
    private void init() {
        Map<String, DataSourceProperties> configMap = springDataSourceProperties.getConfigMap();

        configMap.forEach((k, v) -> {
            log.info("merchantKey = {}, config = {}", k, v);
        });
    }
}
